#include "udp_client.hpp"

using namespace std;

void Usage(char *proc)
{
    std::cout << "Usage:\n\t" << proc << " serverip serverport\n"
              << std::endl;
}

void *recvmessage(void *args)
{
    int sock = *(static_cast<int *>(args));

    while (1)
    {
        // 接受响应
        char buffer[1024];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        int n = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
        if (n > 0)
        {
            buffer[n] = '\0';
            cout << buffer << endl;
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock == -1)
    {
        cerr << "create socket error" << endl;
        exit(SOCKET_ERR);
    }

    // client这里不需要我们自己进行bind，而是在第一次进入内核发送的时候由OS进行自动bind
    // 原因：client的port要随机让OS分配防止client出现启动冲突
    // 那server 为什么要自己bind？
    // 1. server的端口不能随意改变，众所周知且不能随意改变的 2. 同一家公司的port号需要统一规范化

    // 确定server的IP和PORT
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    pthread_t r;
    pthread_create(&r, nullptr, recvmessage, &sock);
    while (1)
    {
        string message;
        cout << "client:";
        // cin >> message;
        getline(cin, message);

        // 发送到服务器上
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
    }

    pthread_join(r, nullptr);
    return 0;
}